package http;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

import java.io.*;
import java.net.Socket;

/**
 * Created by Administrator on 2016/7/23.
 */
public class SocketServerThread extends Thread {
    Socket sock;
//    PrintWriter out = null;
//    DataInputStream dins = null;
    public SocketServerThread(Socket s)
    {
        sock =s ;
    }

    public void run(){
        try {
            InputStream ins = sock.getInputStream();
            DataInputStream dins = new DataInputStream(ins);
            //服务端解包过程
            boolean flag = false;
            while(!flag) {
//            byte flag = dins.readByte();
//            String result = ByteAndHex.bytesToHexString();
//            System.out.println("接收消息类型"+flag);
                PrintWriter out = new PrintWriter(sock.getOutputStream());
                byte[] data = new byte[512];
                dins.read(data);
                String result = ByteAndHex.bytesToHexString(data);
                System.out.println(Thread.currentThread().getName()+"发来的内容是:" + result);


//                out.println(ByteAndHex.hexStringToBytes("ef02"));
                out.println("sgdasdfsafd");
                out.flush();
//                Thread.sleep(3000);
//                dins.close();
//                out.close();
//                sock.close();
//                flag = true;
                break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                sock.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void get(String message) throws IOException {
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod("http://localhost:8999/api/rest/socket/insert/data?result="+message);

        client.executeMethod(method);
        //打印服务器返回的状态
        System.out.println(method.getStatusLine());
        InputStream stream = method.getResponseBodyAsStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        StringBuffer buf = new StringBuffer();
        String line;
        while (null != (line = br.readLine())) {
            buf.append(line).append("\n");
        }
        System.out.println(buf.toString());
        //释放连接
        method.releaseConnection();
    }
}
